/**
 * Created by Administrator on 2017/6/28.
 */

let userDao = require('../mysql/userDao.js');
let log = require('../util/log.js');
let create = require('./create.js');

module.exports = tourist;

function tourist(account, password, platform) {
    this._account = account;
    this._password = password;
    this._platform = platform;
    this._cb = null;
}

tourist.prototype.run = function (cb) {
    this._cb = cb;
    if (this._account) {
        this.login();
    } else {
        this.reg();
    }
};  

tourist.prototype.login = function () {
    let _this = this;
    let userModel = new userDao();
    userModel.inAccount(_this._account, function (err, res) {
        if (res == null) {
            if (_this._password) {
                _this.regNew(_this._account,_this._password); 
            }else{
                _this._cb(null, {'error': 102, 'msg': '账号不存在'}); 
            }   
            return false;
        }   
        if (!userModel.checkPass(_this._password)) {
            _this._cb(null, {'error': 103, 'msg': '密码错误'});
            return false;
        }   
        create.reToken(userModel, null, _this._cb);
        return false;
    });
};

tourist.prototype.regNew = function (account, password) {
    let _this = this; 
    create.user(account, password,function (err, res, token) {
        if (res == null) {
            _this._cb(null, {'error': 105, 'msg': '创建账号失败'});
            return false;
        }   
        var data = {'account': account, 'password': password, 'token': token};
        _this._cb(null, data);
        return false;
    });
};

tourist.prototype.reg = function () {
    let _this = this;
    create.auto(function (err, res, data) {
        if (res == null) {
            _this._cb(null, {'error': 105, 'msg': '创建账号失败'});
            return false;
        }
        _this._cb(null, data);
        return false;
    });
};

